import 'package:flutter/material.dart';
import 'package:flutterapp2/base/base_test_widget.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';

class TestSharedPreferences extends BaseTestWidget {
  GlobalKey key2 = new GlobalKey();

  @override
  String getTitle() {
    return "TestSharedPreferences";
  }

  @override
  Widget getBody(BuildContext context) {
    listen();
    return ListView(
      children: <Widget>[
          FutureBuilder<SharedPreferences>(
              future: SharedPreferences.getInstance(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  // 等这个绘制完成，再计算高度
                  return Text("从sp中获取数据:name = ${snapshot.data.get("name")}");
                } else {
                  return const SizedBox.shrink();
                }
              }),
          FutureBuilder<String>(
              future: getFuture(),
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text("${snapshot.data}");
                } else {
                  return const SizedBox.shrink();
                }
              }),
//          SizedBox(
//            height: 100,
//            width: 100,
//          ),
        RaisedButton(
          key: key2,
          onPressed: () async {
            listen();
            var sharedPreferences = await SharedPreferences.getInstance();
            sharedPreferences.setString("name", "张三");
          },
          child: Text("save数据"),
        ),
      ],
    );
  }

  listen() {
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      var y = getY(key2.currentContext);
      print("top=$y");
      Fluttertoast.showToast(msg: "haha");
    });
  }

  double getY(BuildContext buildContext, {double dy = 0.0}) {
    final RenderBox box = buildContext.findRenderObject();
    // 计算相对tabbar底部的距离
    final topLeftPosition = box.localToGlobal(Offset(0.0, dy));
    return topLeftPosition.dy;
  }

  Future<String> getFuture() async {
    return Future.delayed(Duration(seconds: 2), () => "嘻嘻");
  }
}
